package org.zzk.exception;

import com.google.gson.JsonObject;
import org.zzk.dao.ChessMove;

public class GameException extends RuntimeException {
    private final ErrorType errorType;
    private final String playerId;
    private final String roomId;
    private final transient ChessMove move; // 不序列化

    public enum ErrorType {
        ILLEGAL_MOVE,       // 非法走棋
        WRONG_TURN,         // 回合错误
        ROOM_NOT_FOUND,     // 房间不存在
        GAME_ALREADY_OVER,  // 游戏已结束
        NETWORK_ERROR,      // 网络问题
        PROTOCOL_VIOLATION,  // 协议违规
        CURRENT_NOT_HAVE_PLAYER // 当前无活动玩家
    }

    public GameException(ErrorType errorType, String message) {
        this(errorType, message, null, null, null);
    }

    public GameException(ErrorType errorType, String message,
                         String playerId, String roomId, ChessMove move) {
        super(buildMessage(errorType, message, playerId, roomId));
        this.errorType = errorType;
        this.playerId = playerId;
        this.roomId = roomId;
        this.move = move;
    }

    private static String buildMessage(ErrorType type, String msg,
                                       String playerId, String roomId) {
        return String.format("[%s] 玩家[%s]|房间[%s] - [%s]",
                type.name(),
                playerId != null ? playerId : "null",
                roomId != null ? roomId : "null",
                msg);
    }

    // 转换为网络协议格式
    public JsonObject toProtocolJson() {
        JsonObject json = new JsonObject();
        json.addProperty("error_type", errorType.name());
        json.addProperty("message", getMessage());
        if (playerId != null) json.addProperty("player_id", playerId);
        if (roomId != null) json.addProperty("room_id", roomId);
        if (move != null) json.add("move", move.toJson());
        return json;
    }

    // 常用快捷方法
    public static GameException illegalMove(String playerId, ChessMove move) {
        return new GameException(ErrorType.ILLEGAL_MOVE,
                "不符合棋子走法规则", playerId, null, move);
    }

    public static GameException wrongTurn(String playerId, String roomId) {
        return new GameException(ErrorType.WRONG_TURN,
                "当前不是你的回合", playerId, roomId, null);
    }
}
